// https://www.acwing.com/problem/content/846/

#include <iostream>
#include <queue>

using namespace std;

// 在 2 的基础上，优化存储空间，去除了 dist 二维数组

int m, n;
int board[105][105];
int visited[105][105];
int steps = 0;
int to[4][2] = {{0, -1}, {1, 0}, {-1, 0}, {0, 1}};

void bfs() {
    queue<pair<int, int>> que;
    que.push({0, 0});

    while (!que.empty()) {
        int size = que.size();
        for (int i=0; i<size; i++) {
            auto [x, y] = que.front();
            que.pop();
            if (x == m - 1 && y == n - 1) {
                return;
            }
            for (auto &t: to) {
                int tx = x + t[0], ty = y + t[1];
                if (tx >= 0 && ty >= 0 && tx < m && ty < n && !visited[tx][ty] && !board[tx][ty]) {
                    que.push({tx, ty});
                    visited[tx][ty] = 1; // 一定要在入队列时标记已经使用过
                }
            }
        }
        steps++;
    }
}
/*
5 5
0 1 0 0 0
0 1 0 1 0
0 0 0 0 0
0 1 1 1 0
0 0 0 1 0

[8]

10 10
0 0 0 0 0 0 1 0 0 1
0 0 1 0 0 1 0 0 0 1
0 0 1 0 0 1 0 0 0 0
0 0 0 0 0 0 0 0 0 0
1 1 1 0 0 0 0 1 0 0
0 0 0 0 0 0 1 0 0 1
0 0 0 1 1 1 0 1 1 1
0 0 0 0 0 0 0 0 0 1
0 0 0 0 1 0 1 0 0 0
0 0 0 0 1 0 1 1 1 0

[20]
*/
int main() {
    scanf("%d%d", &m, &n);
    for (int i=0; i<m; i++) {
        for (int j=0; j<n; j++) {
            scanf("%d", &board[i][j]);
        }
    }
    bfs();
    cout<<steps<<endl;
    return 0;
}
